﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.Drawing.Imaging;
using System.IO;

public partial class createRadcode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //定义图片的宽度
        int ImageWidth = 75;
        //定义图片高度
        int ImageHeigh = 28;
        //定义字体，用于绘制文字
        Font font = new Font("Arial", 17, FontStyle.Bold);
        //定义画笔，用于绘制文字
        Brush brush = new SolidBrush(Color.White);
        //创建一个图像
        Bitmap BitImage = new Bitmap(ImageWidth, ImageHeigh);
        //从图像获取一个绘画面
        Graphics graphics = Graphics.FromImage(BitImage);
        //清除整个绘图画面并用颜色填充
        graphics.Clear(ColorTranslator.FromHtml("#59c2f9"));//这里从HTML代码获取color对象
        //定义文字的绘制矩形区域
        RectangleF rect = new RectangleF(2, 2, ImageWidth, ImageHeigh);
        //绘制验证码文字
        graphics.DrawString(CreateCheckCodeString(), font, brush, rect);

        //保存图片为gif格式
        BitImage.Save(Response.OutputStream, ImageFormat.Gif);
        //释放对象
        graphics.Dispose();
        BitImage.Dispose();
    }
    private string CreateCheckCodeString()
    { //定义用于验证码的字符数组
        char[] AllCheckCodeArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M' };
        //定义验证码字符串
        string randomcode = "";
        Random rd = new Random();
        //生成4位验证码字符串
        for (int i = 0; i < 4; i++)
            randomcode += AllCheckCodeArray[rd.Next(AllCheckCodeArray.Length)];
        Session["CheckCode"] = randomcode;
        return randomcode;
    }
}
